package com.killer.gateway.filter;

import io.netty.buffer.UnpooledByteBufAllocator;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.DefaultServerRequest;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class CacheBodyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        //获取请求方法
        String methodValue = serverHttpRequest.getMethodValue();
        if (!StringUtils.equalsIgnoreCase("GET", methodValue)&&!StringUtils.equalsIgnoreCase("DELETE", methodValue)) {
            //如果不是GET请求或者delete请求
            ServerRequest serverRequest = new DefaultServerRequest(exchange);
            //Mono是响应式编程层与层之间传递的对象，Mono.just就是初始化一个Mono对象
            //获取requestBody
            Mono<String> bodyToMono = serverRequest.bodyToMono(String.class);
            return bodyToMono.flatMap(body->{
                //缓存requestBody
                exchange.getAttributes().put("cachedRequestBody", body);
                //重新封装成一个新请求(requestBody只能读取一次)
                ServerHttpRequest newRequest=new ServerHttpRequestDecorator(serverHttpRequest){
                    @Override
                    public HttpHeaders getHeaders() {
                        //封装请求头,将原请求的请求头放入新请求的请求头
                        HttpHeaders httpHeaders=new HttpHeaders();
                        httpHeaders.putAll(super.getHeaders());
                        httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                        return httpHeaders;
                    }

                    @Override
                    public Flux<DataBuffer> getBody() {
                        //封装请求体
                        NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(new UnpooledByteBufAllocator(false));
                        DataBuffer bodyDataBuffer = nettyDataBufferFactory.wrap(body.getBytes());
                        return Flux.just(bodyDataBuffer);
                    }
                };
                //传给后续过滤器使用
                return chain.filter(exchange.mutate().request(newRequest).build());
            });
        }
        //直接放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //优先级，数值越小，优先级越高
        return -99;
    }
}
